﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using RH.Common.Extensions;
using RH.Domain;
using RH.Web.ViewModels;
using RH.Web.Utility;
using RH.Web.ViewModels.UtilityModels;
using AutoMapper;

namespace RH.Web.Areas.Site.Controllers
{
    [Authorize(Roles = "Admin,Site User")]
    public class SavedSearchController : BaseController
    {
		private AppEntities _Context = null;
		private EntityRepository _Repository = null;
        
		#region Constructors
		public SavedSearchController()
		{
			_Context = new AppEntities();
			_Repository = new EntityRepository(_Context);
		}

		public SavedSearchController(UserViewModel currentUser)
			: base(currentUser)
        {
			_Context = new AppEntities();
			_Repository = new EntityRepository(_Context);
        }
		#endregion Constructors

		#region Action Methods
        public ActionResult Index()
        {
            return View("List", BuildSavedSearchListConfig());
        }

		public ActionResult List()
        {
            return View(BuildSavedSearchListConfig());
        }

		/// <summary>
        /// Deletes a Saved Search object from Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns>
        /// Returns:
        ///  -1 If the entity is not found in the databae
        ///  -2 If the Saved search is not belongs to the currently logged in user
        ///  +1 If everything is ok, then returs 1
        /// </returns>
		[HttpPost]
		public int Delete(int id)
        {
            SavedSearch entity = _Context.SavedSearches.FirstOrDefault(P => P.ID == id);
            if (entity == null)
                return -1;
            if (entity.UserID != LoggedInUser.ID)
                return -2;

            _Context.DeleteObject(entity);
            _Context.SaveChanges();

            return 1;
        }		
		#endregion Action Methods
		
		#region Helper Methods

		/// <summary>
        /// Builds a ListConfig object with a list of SavedSearch
        /// </summary>
        /// <returns></returns>
		private ListConfig BuildSavedSearchListConfig()
		{
			UtilityDAO dao = new UtilityDAO();
            RH.Domain.DbParameter[] parameters = new[]{
                new RH.Domain.DbParameter("@UserID", LoggedInUser.ID)
            };
            DataSet ds = dao.GetDataSet(DbObject.SP.GET_SAVEDSEARCH_LIST, parameters, true);
            ListConfig listConfig = new ListConfig(ds.Tables[0], null);
            return listConfig;
		}

        #endregion			
    }
}


